/*
 * Copyright 2009 Jiwei Xu (http://www.xujiwei.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

provide("Objects.ArcObj");

require("Objects.FigureObj");

ArcObj = Class(FigureObj, (function() {

    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    return {
        Initialize : function() {
            this.Base();

            this.Handles = [];
            this.IsCircle = false;
        },

        MoveHandle : function(index, delta) {
            this.Handles[index].X += delta.X;
            this.Handles[index].Y += delta.Y;
        },

        CalcAngles : function() {
            var dx1 = this.Handles[1].X - this.Handles[0].X,
                dy1 = this.Handles[1].Y - this.Handles[0].Y;

            this.Radius = Math.sqrt(dx1*dx1 + dy1*dy1);

            this.StartAngle = dx1 === 0 ? 0 : Math.atan(dy1 / dx1);
            this.EndAngle = this.StartAngle + Math.PI * 2;

            if (!this.IsCircle) {
                var dx2 = this.Handles[2].X - this.Handles[0].X,
                    dy2 = this.Handles[2].Y - this.Handles[0].Y;

                this.EndAngle = Math.atan(dy2 / dx2);
            }
        },

        Draw : function(ctx) {
            if (this.Handles.length + (this.IsCircle ? 1 : 0) < 3) {
                return;
            }

            this.SetStyles(ctx);

            this.CalcAngles();

            ctx.beginPath();
            ctx.arc(this.Handles[0].X, this.Handles[0].Y, this.Radius, this.StartAngle, this.EndAngle, false);
            
            if (this.IsFill) {
                ctx.fill();
            }
            ctx.stroke();
        },

        HitTest : function(pt) {
            this.CalcAngles();

            context.beginPath();
            context.arc(this.Handles[0].X, this.Handles[0].Y, this.Radius, this.StartAngle, this.EndAngle, false);
            context.closePath();

            return context.isPointInPath(pt.X, pt.Y);
        }
    };
})());